/*
*    Qizx/open 3.0 beta
*
* This code is the open-source version of Qizx.
* Copyright (C) 2004-2009 Axyana Software -- All rights reserved.
*
* The contents of this file are subject to the Mozilla Public License 
*  Version 1.1 (the "License"); you may not use this file except in 
*  compliance with the License. You may obtain a copy of the License at
*  http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
*  WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
*  for the specific language governing rights and limitations under the
*  License.
*
* The Initial Developer of the Original Code is Xavier Franc - Axyana Software.
*
*/
using System;
using EvaluationException = System.Qizx.Api.EvaluationException;
using ComparisonContext = System.Qizx.XQuery.ComparisonContext;
using EvalContext = System.Qizx.XQuery.EvalContext;
using ExprDisplay = System.Qizx.XQuery.ExprDisplay;
using ModuleContext = System.Qizx.XQuery.ModuleContext;
using XQItem = System.Qizx.XQuery.XQItem;
namespace System.Qizx.XQuery.Op
{
	
	/// <summary> Stores the information for one 'order by' clause.</summary>
	public class OrderSpec:Expression, ComparisonContext
	{
		virtual public int ImplicitTimezone
		{
			get
			{
				return 0;
			}
			
		}
		public Expression key;
		public string collation;
		private System.Globalization.CompareInfo collator;
		public bool descending = false;
		public bool _emptyGreatest = false;
		
		public OrderSpec(Expression key)
		{
			this.key = key;
		}
		
		public override Expression Child(int rank)
		{
			return (rank == 0)?key:null;
		}
		
		public override void  Dump(ExprDisplay d)
		{
			d.header(this);
			d.property("descending", "" + descending);
			d.property("emptyGreatest", "" + _emptyGreatest);
			d.property("collation", collation);
			d.child("key", key);
		}
		
		public override Expression StaticCheck(ModuleContext context, int flags)
		{
			key = context.staticCheck(key, 0);
			type = key.getType();
			collator = context.getCollator(collation);
			if (collator == null && collation != null)
				context.error("XQST0076", key, "unknown collation " + collation);
			return this;
		}
		
		// null key means empty
		internal virtual int compare(XQItem key1, XQItem key2, EvalContext context)
		{
			int cmp = 0;
			if (key1 == null)
				cmp = (key2 == null)?0:(_emptyGreatest?1:- 1);
			else if (key2 == null)
				cmp = _emptyGreatest?- 1:1;
			else
				cmp = key1.CompareTo(key2, this, 0);
			// TODO: deal with NaN
			return descending?- cmp:cmp;
		}
		
		public virtual System.Globalization.CompareInfo getCollator()
		{
			return collator;
		}
        public bool emptyGreatest() {
            return _emptyGreatest;
        }
	}
}